<?php

//Getting the parameters
$queryType = $_POST["queryType"];
$queryParam = $_POST["queryParam"];

//This is a backdoor for web access, need sanitazion
if ($queryType == '') {
  $queryType = htmlspecialchars_decode($_GET["queryType"]);
  $queryParam = htmlspecialchars_decode($_GET["queryParam"]);
 }

//Make a MySQL connection
$username = "sretika2";
$password = "sretika2dbpw";
$host = "csil-projects.cs.uiuc.edu";
$db = "GermanShepherd";

$connection = mysql_connect($host, $username, $password);

//Check connection status
if (!$connection)
  {
    die("Error : MySQL connection cannot be established\n" . mysql_error());
  }
  
mysql_select_db($db, $connection);

//Redirect query to handlers
if ($queryType != '')
  {
    if ($queryType == "getFileList") {
      getFileList();
    }
    else if($queryType == "getHolderList") {
      getHolderList();
    }
    else if($queryType == "register") {
      register();
    }
    else {
      echo "ARE YOU STUPID? <br>";
    }

  }

//Done, close the connection
mysql_close($connection);



/////////////////////////////////////////////////HELPER FUNCTIONS/////////////////////////////////////////////



function register() {
  
  //To scope the variables as the global one
  global $queryParam;

  $myxml = new DomDocument();
  $myxml->loadXML($queryParam);
  
  $username = $myxml->getElementsByTagName("Username")->item(0)->nodeValue;
  $port = $myxml->getElementsByTagName("Port")->item(0)->nodeValue;

  $fileList = $myxml->getElementsByTagName("File");
  
  $Ip = $_SERVER['REMOTE_ADDR'];
  $query = mysql_query("select * from PeerList where Username='$username'");
  $row = mysql_fetch_array($query);

  $time = time();
    
  //Update user info
  if($row) {
    if ($port == NULL || $port == '') {
      if(!mysql_query("update PeerList set Ip='$Ip',Timestamp=$time where Username='$username'")) 
	die("<Status>ERROR : Cannot update Ip of user $username".mysql_error()."</Status>");
    }
    else if(!mysql_query("update PeerList set Ip='$Ip', Port='$port',Timestamp=$time where Username='$username'")) 
      die("<Status>ERROR : Cannot update IP and Port of user $username".mysql_error()."</Status>");
  }
  else
    {
        if(!mysql_query("insert into PeerList (Username, Ip, Port, Timestamp) values ('$username', '$Ip', '$port', '$time')")) 
	  die("<Status>ERROR : Cannot insert user $username to PeerList</Status>");
    }
  
  //Delete the holder from FileHolder
  mysql_query("delete from FileHolder where Username='$username'");

  //Add user's file list
  foreach ($fileList as $file) {
    $filename = $file->getElementsByTagName("Name")->item(0)->nodeValue;
    $filesize = $file->getElementsByTagName("Size")->item(0)->nodeValue;
    
    //Insert to fileList
    if(!mysql_query("insert into FileList (Filename, Filesize, Date) values ('$filename', $filesize, $time) on duplicate key update date=$time")){
      die("<Status>ERROR : Cannot insert the file $filename</Status>");
    }

    //Get file id
    $filequery = mysql_query("select FileID from FileList where Filename='$filename' and Filesize=$filesize");
    if (!$filequery)
      die("<Status>Something wrong when updating file $filename</Status>");
    
    $filequeryrow = mysql_fetch_array($filequery);
    $fileid = $filequeryrow['FileID'];

    //Insert to FileHolder
    mysql_query("insert ignore into FileHolder (Username, FileID) values ('$username', $fileid)");
  }

  echo "<Status>SUCCESS</Status>";
}


function getFileList() {
  
  //To scope the variables as the global one
  global $queryParam;

  $myxml = new DomDocument();
  $myxml->loadXML($queryParam);
  
  $filename = $myxml->getElementsByTagName("getFileList")->item(0)->nodeValue;
  $filename = str_replace(" ", "%", $filename);

  $Ip = $_SERVER['REMOTE_ADDR'];

  $query = mysql_query("select FileID,Filename,Filesize from FileList natural join FileHolder where Filename like '%$filename%' and Username not in (select Username from PeerList where Ip='$Ip')");
 

  $out = "<FileList>";

  while($row = mysql_fetch_array($query)) {
    $out = $out."<File><ID>".$row['FileID']."</ID><Name>".$row['Filename']."</Name><Size>".$row['Filesize']."</Size></File>";
  }

  $out = $out."</FileList>";
  echo $out;
}


function getHolderList() {
  
  //To scope the variables as the global one
  global $queryParam;

  $myxml = new DomDocument();
  $myxml->loadXML($queryParam);
  
    
  $FileID = $myxml->getElementsByTagName("getHolderList")->item(0)->nodeValue;

  $Ip = $_SERVER['REMOTE_ADDR'];

  $query = mysql_query("select Username,Ip,Port from FileHolder natural join PeerList where FileID=$FileID and Ip!='$Ip'");
  $out = "<HolderList>";

  while($row = mysql_fetch_array($query)) {
    $out = $out."<Holder><Name>".$row['Username']."</Name><Ip>".$row['Ip']."</Ip><Port>".$row['Port']."</Port></Holder>";
  }

  $out = $out."</HolderList>";
  echo $out;
}

?>































